#include "stdio.h"
#include "string.h"

int n,m,num;

int count(char *s)
{
	int i,j,tot=0;
	char ch;

	for (i=0;i<n-1;i++)
	{
		for (j=i+1;j<n;j++)
		{
			if (s[i]>s[j]) tot++;
		}


	}
	return tot;


}




void main()
{
	int i,j,k;
	char s[101][51];
	int sort[101],large,site;

	scanf("%d",&num);

	for (k=1;k<=num;k++)
	{
		memset(s,0,sizeof(s));
		memset(sort,0,sizeof(sort));
		scanf("%d%d",&n,&m);

		if (k!=1) printf("\n");

		for (i=1;i<=m;i++)
		{
			scanf("%s",s[i]);
			sort[i]=count(s[i]);
		}

		for (i=1;i<=m;i++)
		{
			large=sort[1];
			site=1;
			for (j=2;j<=m;j++)
			{
				if (large>sort[j])
				{
					large=sort[j];
					site=j;
				}
			}
			printf("%s\n",s[site]);
			sort[site]=5000;

		}






	}


}